package com.rky.crowd.mvc.config;

import com.rky.crowd.service.api.AdminService;
import com.rky.crowd.service.api.AuthService;
import com.rky.crowd.service.api.RoleService;
import entity.Admin;
import entity.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 0x_Jss
 * @date 2022年02月16日 16:08
 * @description
 */
@Component
public class CrowdUserDetailsService implements UserDetailsService {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private AuthService authService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        Admin admin = adminService.getAdminByLoginAcct(username);
        Integer adminId = admin.getId();
        List<Role> assignedRoleList = roleService.getAssignedRole(adminId);
        List<String> authNameList = authService.getAssignedAuthNameByAdminId(adminId);
        List<GrantedAuthority> authorities = new ArrayList<>();

        //遍历assignedRoleList存入角色信息
        for (Role role : assignedRoleList){
            String roleName = "ROLE_" + role.getName();
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(roleName);
            authorities.add(simpleGrantedAuthority);
        }
        //遍历
        for (String authName : authNameList){
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(authName);
            authorities.add(simpleGrantedAuthority);
        }
        //封装securityAdmin对象
        SecurityAdmin securityAdmin = new SecurityAdmin(admin,authorities);
        return securityAdmin;
    }
}